#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>


#define die(x,y) {perror ((x)); exit ((y));}
char pty_name[20];

int allocate_pty () {
  struct stat stb ;
  int fd , i ;

   for ( i = 1 ; i < 256 ; i++ )
   {
       sprintf (pty_name, "/dev/ptyp%d", i ) ;
       if ( stat ( pty_name , & stb ) < 0 )
           return -1;

       fd = open (pty_name, O_RDWR | O_NONBLOCK, 0);
       if ( fd >= 0 )
       {
           pty_name [5] = 't' ;                    /* change /dev/pty?? to /dev/tty?? */
           if ( access ( pty_name, W_OK | R_OK ) != 0 )
           {
               close (fd);
                   continue ;
           }
           return fd;
       }
   }
   return -1 ;
}

int allocate_pair (int filedes[2]) {
  char *slave;
  int fd, om = open ("/dev/ptmx", O_RDWR);
  if (om < 0) die ("/dev/ptmx", 1);
  if (grantpt (om) < 0) die ("grantpt", 2);
  if (unlockpt (om) < 0) die ("unlockpt", 3);
  slave = ptsname (om);
  if (slave == NULL) die ("ptsname", 4);
  
  fd = open (slave, O_RDWR);
  if (fd < 0) die ("slaveopen", 5);

  filedes[0] = om;
  filedes[1] = fd;
  return fd;
}


int main (int argc, char **argv) {
  int filedes[2];
  char *tmp[20];
  int fd;

  close (0); close (1);
  
  fd = allocate_pair (filedes);

  perror ("alooo");
  //FILE *f = fdopen (fd, "w+");
  //if (f == NULL)  
  //  perror ("fdopen");

  //fprintf (f, "The tty found is #%d  %s\n", fd, pty_name);
  
  //read (filedes[1], tmp, 10);
  write (filedes[0], "ALALALALALALLALAL", 10);
  printf ("fdto e %d, errno e %d\n", fd, errno);
  perror ("ima li greshka");
  return 0;
}
